package com.sat.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.sat.goods.dao.BrandMapper;
import com.sat.goods.dao.CategoryMapper;
import com.sat.goods.dao.SkuMapper;
import com.sat.goods.dao.SpuMapper;
import com.sat.goods.pojo.*;
import com.sat.goods.service.GoodsService;
import entity.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private IdWorker idWorker;  //分布式自增长ID

    /**
     * 回滚库存
     * @param id
     * @param num
     * @return
     */
    @Override
    public Integer rollBackSkuStock(Long id, Integer num) {

        return skuMapper.rollBackSkuStock(id,num);
    }

    /**
     * 减少库存
     * @param id
     * @param num
     * @return
     */
    @Override
    public Integer updateSkuNum(Long id,Integer num) {

        Sku sku = new Sku();
        sku.setId(id);
        sku.setNum(num);
        //返回值是更新成功的条数，如果失败，数值为0
        Integer skuNum = skuMapper.updateSkuNum(sku);
        if(skuNum == 0){
            throw new RuntimeException("减少库存失败");
        }

        return skuNum;
    }

    @Override
    public GoodsVo findById(Long skuid) {

        Sku sku = skuMapper.selectByPrimaryKey(skuid);
        Spu spu = spuMapper.selectByPrimaryKey(sku.getSpuId());
        GoodsVo goodsVo = new GoodsVo();
        goodsVo.setSku(sku);
        goodsVo.setSpu(spu);
        return goodsVo;
    }

    /**
     * 添加商品，即添加spu和sku，Goods包装类包含了spu和sku。前端传过来的Good只有部分字段有值，其余值自己补充
     * @param goods
     */
    @Transactional
    @Override
    public void saveGoods(Goods goods) {
        //增加Spu 补齐Spu id
        Spu spu = goods.getSpu();
        spu.setId(idWorker.nextId());
        spuMapper.insertSelective(spu);

        //增加Sku，补齐空白的和数据库没有默认值的字段
        //获取Sku集合
        List<Sku> skuList = goods.getSkuList();
        //封装skuid、创建时间、更新时间、spuId、categoryId、categoryName、brandName、SKU名称
        Date date = new Date();
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());

        for (Sku sku : skuList) {

            sku.setId(idWorker.nextId());
            sku.setCreateTime(date);
            sku.setUpdateTime(date);
            sku.setSpuId(spu.getId());
            sku.setCategoryId(spu.getCategory3Id());
            sku.setCategoryName(category.getName());
            sku.setBrandName(brand.getName());

            //规格是一个json串，将规格转换成Map
            Map<String,String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
            //获取Spu的名字
            String name = spu.getName();
            //循环组装Sku的名字，Sku名字由Spu名+规格的值组成
            for (Map.Entry<String, String> entry : specMap.entrySet()) {
                name+="  "+entry.getValue();
            }
            sku.setName(name);

            skuMapper.insertSelective(sku);

        }

    }

    @Override
    public void pull(Long spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if(spu.getIsDelete().equals("2")){
            throw new RuntimeException("此商品已删除！");
        }
        spu.setIsMarketable("2");//下架状态
        spuMapper.updateByPrimaryKeySelective(spu);

    }

    @Override
    public int putMany(Long[] ids) {

        Spu spu = new Spu();
        spu.setIsMarketable("1");//上架，只是修改spu信息，不是新增
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andIn("id", Arrays.asList(ids));//批量修改id在该数组中的spu
        //下架   只修改已经下架的spu，上架状态的不需要修改
        criteria.andEqualTo("isMarketable","2");
        //审核通过的
        criteria.andEqualTo("status","1");
        //非删除的
        criteria.andEqualTo("isDelete","1");
        return spuMapper.updateByExampleSelective(spu, example);

    }
}
